package com.qf.admin.service.system.impl;

import com.qf.admin.service.system.SysUserService;
import com.qf.common.domain.admin.dos.SysUser;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.qf.common.domain.admin.dos.SysRole;
import javax.annotation.Resource;
import java.util.stream.Collectors;

/**
 * @author : sin
 * @date : 2024/6/11 13:01
 * @Description : 用户登录实现
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    @Resource
    SysUserService sysUserService;

    /**
     * 通过用户名查询用户信息
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = sysUserService.selectUserByUsername(username);
        // TODO 后期考虑使用断言
        if(user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        //将数据库中的角色拆分成SpringSecurity结构
        String roles = user.getRoles().stream().map(SysRole::getCode).collect(Collectors.joining(","));
        user.setAuthorities(AuthorityUtils.commaSeparatedStringToAuthorityList(roles));
        return user;
    }
}